package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.dao.MyBaseMapper;
import com.example.demo.excel.ExcelUtil;
import com.example.demo.service.MyService;
import com.example.demo.util.GlobalUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class MyServiceImpl implements MyService {


    @Autowired
    private SqlSessionFactory sessionFactory;


    @Override
    public int save(Object entity) {
        MyBaseMapper baseMapper = getMapper(StringUtils.uncapitalize(entity.getClass().getSimpleName()));
        return baseMapper.insert(entity);
    }

    @Override
    public List<Object> list(QueryWrapper queryWrapper) {
        MyBaseMapper baseMapper = getMapper(StringUtils.uncapitalize(queryWrapper.getEntityClass().getSimpleName()));
        return baseMapper.mySelectList(queryWrapper);
    }

    @Override
    public int delete(String model, List<Long> ids) {
        MyBaseMapper baseMapper = getMapper(model);
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int update( Object entity) {
        MyBaseMapper baseMapper = getMapper(StringUtils.uncapitalize(entity.getClass().getSimpleName()));
        return baseMapper.updateById(entity);
    }

    @Override
    public Object get(String model, Long id) {
        MyBaseMapper baseMapper = getMapper(model);
        return baseMapper.myGet(id);
    }

    @Override
    public void downLoad(QueryWrapper queryWrapper, HttpServletResponse response) {
        List list =  list(queryWrapper);
        ExcelUtil.write(queryWrapper.getEntityClass(),response,list);
    }

    @SneakyThrows
    @Override
    public List upload(String model, MultipartFile file) {
        Class clazz = GlobalUtil.entityClassMap.get(model);
        List list = ExcelUtil.read(clazz,file);
        MyBaseMapper mapper = getMapper(model);
        for (int i = 0; i < list.size(); i++) {
            if(clazz.getMethod("getId").invoke(list.get(i))!=null){
                mapper.updateById(list.get(i));
            }else {
                mapper.updateById(list.get(i));
            }

        }
        return ExcelUtil.read(clazz,file);
    }

    public MyBaseMapper getMapper(String model){
        return (MyBaseMapper)sessionFactory.openSession(true).getMapper(GlobalUtil.mapperClassMap.get(model));
    }
}
